# -*- coding: cp866 -*-

import MSLogger
from datetime import timedelta, datetime
from time import time

TIME_FORMAT_MAGIC = '%d%m%Y_%H%M%S'     #time format descriptor used in magic api
TIME_FORMAT_MAGICDB = '%Y-%m-%d %H:%M:%S'
TIME_FORMAT_PCN = '%Y-%m-%d %H:%M:%S'   #time format descriptor used in pcn db
TIME_FORMAT_CESAR = '%d.%m.%Y %H:%M:%S'
MS_MSGID_TO_CONTACTID = {
    '13':'1103',
    '22':'1101'
}
MS_BOLID_TO_CONTACTID = {
    'ВЗЛОМКОРПУСА':'3831',
    'ВОССТ.КОРПУСА':'3833',
    'ПОЖ':'1101',
    'ПОЖАР':'1101',
	'СРАБОТКАДАТЧИКА':'1101',
    'СБРОСТРЕВОГИШС':'1103',
    'ВНИМАНИЕ':'1181',
    'ТРЕВОГА':'1231',
	'ТИХАЯТРЕВОГА':'1221',
	'ТРЕВОГАВХОДА':'1341',
	'ИЗМ.ДАТЫ':'6253',
	'ВЗЯТШС':'4003',
	'СНЯТШС':'4011',
	'ПРОГРАММИРОВАНИЕ':'6271',
	'СБРОСПРИБОРА':'3051',
	'ОБР':'3311',
	'КЗ':'3321',
	'АВПИТ':'3011',
	'ВОССТ':'3013'
}

class MSEvent:
    def __init__(self):
        #event internal identificator
        self.eventId = 0
        #event internal type
        self.eventType = 0
        #object owner of the event - who generated
        self.objectId = 0
        #user owner of the event - who this object belongs to
        self.userOwnerId = 0
        #user writer of the event - who put into DB
        self.userWriterId = 0
        #when event has been received
        self.eventReceiveTime = datetime.fromtimestamp(time())
        #when event has been generated
        self.eventGenerateTime = self.eventReceiveTime

#STATIC EVENT DATA
        #does event have static data
        self.hasStatic = False
        #event type in ContactId's notation
        self.contactIdType = 0
        self.contactIdFull = 0
        self.contactIdZona = 0
        self.contactIdGroup = 0

#MOBILE EVENT DATA
        #does event have gps coordinates
        self.hasMobile = False
        #TBD describe coordinate notation and speed measurements
        self.GPSLatitude = 0.0
        self.GPSLongitude = 0.0
        self.GPSSpeed = 0.0

    def __hash__(self):
        return self.eventId

    def __cmp__(self, y):
        if y == None:
            return 1
        if self.eventGenerateTime > y.eventGenerateTime:
            return 1
        if self.eventGenerateTime < y.eventGenerateTime:
            return -1
        if self.eventId > y.eventId:
            return 1
        if self.eventId < y.eventId:
            return -1
        return 0

    def fromPGSM(self, rawEvent):
        global MS_MSGID_TO_CONTACTID
        global TIME_FORMAT_MAGIC
        self.hasStatic = True
        self.contactIdType = MS_MSGID_TO_CONTACTID.get(str(rawEvent['type']), None)
        if self.contactIdType == None:
            raise Exception('unknown PGSM type %s' % (str(rawEvent['type'])))
        self.eventGenerateTime = datetime.strptime(rawEvent['datetime'], TIME_FORMAT_MAGIC)
        #self.eventId = rawEvent['eventInternalId']

    def fromPGSM_AUTOTEST(self, rawEvent):
        global TIME_FORMAT_MAGIC
        self.hasStatic = True
        self.contactIdType = {'98':'6021'}.get(str(rawEvent['type']), None)
        if self.contactIdType == None:
            raise Exception('unknown PGSM type %s' % (str(rawEvent['type'])))
        self.eventGenerateTime = datetime.strptime(rawEvent['datetime'], TIME_FORMAT_MAGIC)
        self.eventGenerateTime = self.eventReceiveTime
        #self.eventId = rawEvent['eventInternalId']


    def fromBolid(self, rawEvent):
        global MS_BOLID_TO_CONTACTID
        global TIME_FORMAT_MAGIC
        self.hasStatic = True

        rawParsed   = rawEvent['type'].split('|')
        rawType     = rawParsed[2].replace(' ', '').decode('cp866').encode('u8')
        rawZone     = rawParsed[3].replace(' ', '')
        rawZone     = rawZone.split('/')
        if len(rawZone) == 2: self.contactIdZona = str(rawZone[1])
        rawGroup    = rawParsed[4].replace(' ', '')
        if len(rawGroup) > 0: self.contactIdGroup = str(rawGroup)

        self.contactIdType = MS_BOLID_TO_CONTACTID.get(str(rawType), None)
        if self.contactIdType == None:
            raise Exception('unknown BOLID type %s' % (str(rawType)))
        self.eventGenerateTime  = datetime.strptime(rawEvent['datetime'], TIME_FORMAT_MAGIC)

    def fromContactId(self, rawEvent):
        self.hasStatic = True
        cid = rawEvent['value']
        contactId_Object = cid[2:6]
        contactId_EType = cid[6:7]
        contactId_Type = cid[7:10]
        contactId_Group = cid[10:12]
        contactId_Zona = cid[12:15]
        self.contactIdFull = cid
        self.contactIdType = "%s%s" % (contactId_Type, contactId_EType)
        self.contactIdGroup = str(contactId_Group)
        self.contactIdZona = str(contactId_Zona)
        self.objectId = int(contactId_Object)
        self.eventGenerateTime = datetime.strptime(rawEvent['date'], TIME_FORMAT_MAGIC)
        #self.eventId = rawEvent['eventInternalId']

    def fromGPSPoint(self, rawEvent):
        self.hasMobile = True
        #we should transfer LAT and LON
        #LAT
        ddd = float(rawEvent['lat'])
        self.GPSLatitudeOrig = ddd
        dd = int(ddd)
        mm = int((ddd - dd)*60)
        ss = str(((ddd - dd)*60 - mm)*60)
        mm = str(mm)
        if (len(mm)) < 2:
            mm = '0%s' % (mm[0])
        dd = str(dd)
        self.GPSLatitude = dd[0:2] + mm[0:2] + '.' + ss.replace('.','')[0:5]
        #LON
        ddd = float(rawEvent['lon'])
        self.GPSLongitudeOrig = ddd
        dd = int(ddd)
        mm = int((ddd - dd)*60)
        ss = str(((ddd - dd)*60 - mm)*60)
        mm = str(mm)
        if (len(mm)) < 2:
            mm = '0%s' % (mm[0])
        dd = str(dd)
        self.GPSLongitude = dd[0:2] + mm[0:2] + '.' + ss.replace('.','')[0:5]
        self.GPSSpeed = rawEvent['speed']
        self.eventGenerateTime = datetime.strptime(rawEvent['date'], TIME_FORMAT_MAGIC)
        #self.eventId = rawEvent['eventInternalId']


class MSObject:
    def __init__(self):
        self.objectSKey = ''
        self.objectName = ''
        self.objectMSId = 0
        self.objectPCNId= 0

        self.lastEvent_PGSM     = None
        self.lastEvent_ContactId= None
        self.lastEvent_GPS      = None
        self.lastEvent_Bolid    = None


        self.canClearPGSMEvents = False
        self.canClearContactIdEvents = False
        self.canClearBolidEvents = False

        self.eventsPGSM         = []
        self.eventsContactId    = []
        self.eventsGPS          = []
        self.eventsBolid        = []
		
        self.cameOOS = False
        self.enableOfflineCritical = False

    def __hash__(self):
        return self.objectMSId
